﻿using System.Collections.Generic;
using System.Reflection;

namespace Devonline.Core
{
    public class MemberEqualityComparer<T> : IEqualityComparer<T>
    {
        public bool Equals(T x, T y)
        {
            var propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var propertyInfo in propertyInfos)
            {
                var valueX = propertyInfo.GetValue(x);
                var valueY = propertyInfo.GetValue(y);
                if (!(propertyInfo.PropertyType.IsValueType || valueX == valueY) || (propertyInfo.PropertyType.IsValueType && valueX.ToString() != valueY.ToString()))
                {
                    return false;
                }
            }

            return true;
        }

        public int GetHashCode(T obj)
        {
            return obj.GetHashCode();
        }
    }
}
